package com.tairanchina.md.elife.rabbit.client.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * Created by lxliuxuan on 2017/2/20.
 */
public class ObjectHandlerUtil {
    private static Logger logger = LoggerFactory.getLogger(ObjectHandlerUtil.class);
    /**
     * 消息编码算法
     *
     * @param obj
     * @return
     */
    public static byte[] handlerEncode(Object obj) throws Exception
    {
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        byte[] result = null;
        try
        {
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            result = bos.toByteArray();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            logger.error("消息编码失败。e:{}---data:{}", e, obj);
            throw new Exception(e);
        }
        finally
        {
            try
            {
                if (bos != null)
                {
                    bos.close();
                }
            }
            catch (IOException e1)
            {
                e1.printStackTrace();
                logger.error("数据输出流1关闭失败。e:{}", e1);
            }

            try
            {
                if (oos != null)
                {
                    oos.close();
                }
            }
            catch (IOException e2)
            {
                e2.printStackTrace();
                logger.error("数据输出流2关闭失败。e:{}", e2);
            }
        }
        return result;
    }


    /**
     * 消息解码算法
     *
     * @param bytes
     * @return
     */
    public static Object handlerDecode(byte[] bytes) throws Exception
    {
        ByteArrayInputStream bin = null;
        ObjectInputStream oin = null;
        Object object = null;
        try
        {
            bin = new ByteArrayInputStream(bytes);
            oin = new ObjectInputStream(bin);
            object = oin.readObject();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            logger.error("消息解码失败。e:{}---data:{}", e, bytes);
            throw new Exception(e);
        }
        finally
        {
            try
            {
                if (bin != null)
                {
                    bin.close();
                }
            }
            catch (IOException e1)
            {
                e1.printStackTrace();
                logger.error("数据输入流1关闭失败。e:{}", e1);
            }

            try
            {
                if (oin != null)
                {
                    oin.close();
                }
            }
            catch (IOException e2)
            {
                e2.printStackTrace();
                logger.error("数据输入流2关闭失败。e:{}", e2);
            }
        }
        return object;
    }
}
